package com.atguigu.yygh.order.controller;

import com.atguigu.yygh.common.result.R;
import com.atguigu.yygh.enums.PaymentTypeEnum;
import com.atguigu.yygh.order.service.PaymentService;
import com.atguigu.yygh.order.service.WeixinService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

/*==========================================
      时 间:   2022-03-18
      讲 师:   刘  辉
      描 述:   尚硅谷教学团队
 ==========================================*/
@RestController
@RequestMapping("/api/order/weixin")
public class WeixinController {


    @Autowired
    private WeixinService weixinService;
    @Autowired
    private PaymentService paymentService;

    @GetMapping("/createNative/{orderId}")
    public R createNative(@PathVariable Long orderId){
        Map<String,Object> result =weixinService.createNative(orderId);
        return R.ok().data(result);
    }
    //查询订单状态: 1.支付失败 2.支付中... 3.支付成功
    @GetMapping(value = "/queryPayStatus/{orderId}")
    public R queryPayStatus(@PathVariable Long orderId){
       Map<String,String> map= weixinService.queryPayStatus(orderId);
       if(map == null){
           return R.error().message("支付失败");
       }
        if(map.get("trade_state").equals("SUCCESS")){
            //更新订单的状态
            //更新支付记录的支付状态和其他字段
            String out_trade_no = map.get("out_trade_no");
            paymentService.paySuccess(out_trade_no, PaymentTypeEnum.WEIXIN.getStatus(), map);
            return R.ok().message("支付成功");
        }
        return R.ok().message("支付中");

    }
}
